//
//  ArticleDetailTableViewController.swift
//  LearnDemo
//
//  Created by 振轩 on 2018/4/9.
//  Copyright © 2018年 振轩. All rights reserved.


//文章详情控制器。


class ReqMode: NSObject {
    var courseId :NSInteger = 0
    var staffId :NSInteger = 0
    var staffType :NSInteger = 0
    
    
    
}

let articledetail = "articledetail"
let attatchment = "attatchMent"
import UIKit

class ArticleDetailTableViewController: UITableViewController {
    //weak var tempSelf = self
    var rowH:CGFloat = 0{
        didSet{
            if rowH>0 {
                self.tableView.reloadData()
            }
            
            
        }
        
        
    }
    var attatchMentLabel = UILabel.init(frame: CGRect.init(x: 5, y: 0, width: 100, height: 40))
    var titleView:VideoTitleView?
    var ReqM:ReqMode?
    var data:ArticleDetail?
    var currentPlayTime:NSInteger = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        loadData()
        //NotificationCenter.default.addObserver(self, selector: #selector(refreshHeight), name: NSNotification.Name.init("refresh"), object: nil)
        
    }
    
    @objc func refreshHeight(){
        
        
        tableView.reloadData()
    }

    override func viewWillAppear(_ animated: Bool) {
        navigationController?.navigationBar.isHidden = false
    }
    

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return 2
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 0 {
            return 1
        }else{
            return  (data?.attachFiles?.count) ?? 0
        }
    }

 
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: articledetail, for: indexPath) as! ArticleDetailCell
            
          
            if data != nil{
                cell.mode = data
                
             cell.reloadCallBack =  { height in
                
                if height == self.rowH {
                    
                    return
                    
                }else{
                    
                    self.rowH = height
                    
                    
                    self.tableView.reloadData()

                    
                }
                

                }
                
            }
            
            
            return cell
        }else{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: attatchment, for: indexPath) as! attachmentCell
            cell.mode = data?.attachFiles![indexPath.row] as! AttatchMode
            return cell
            
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if data != nil{
            //let maxSize = CGSize(width: kScreenW-40, height: CGFloat(MAXFLOAT))
               let height = self.rowH
               //return cellHH
             
                print("********&&&&&&&&&*********")
                print(height)
                print("********&&&&&&&&&*********")
                
                //return
            
                return CGFloat(height+120)
                
                
                
            }else{
                
                return 60
            }
            
        }else{
            
            return 80
        }
    }
    
    
 }


extension ArticleDetailTableViewController{
    
    func setUpUI(){
        
        tableView.register(UINib(nibName: "attachmentCell", bundle: nil), forCellReuseIdentifier: attatchment)
        
        tableView.register(UINib(nibName: "ArticleDetailCell", bundle: nil), forCellReuseIdentifier: articledetail)
        navigationItem.title = "在线学习"
        
        tableView.tableFooterView = UIView()
    }
    func calculateCell(){
        
    }
    func getLabHeigh(labelStr:String,font:UIFont,width:CGFloat) -> CGFloat {
        
        let statusLabelText: NSString = labelStr as NSString
        
        let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
        
        let dic = NSDictionary(object: font, forKey: kCTFontAttributeName as! NSCopying)
        
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any] , context: nil).size
        
        return strSize.height
        
    }
    func loadData(){
        
        var params = [String:AnyObject]()
        params["courseId"] = ReqM?.courseId as AnyObject
        params["staffId"] = ReqM?.staffId as AnyObject
        params["staffType"] = ReqM?.staffType as AnyObject
        
        let API:BaseReqApi = BaseReqApi.init(requestUrl: "/index.php/FoodCheckApi/courseDetail.json", andrequestTime: 5, andParams: params as! [AnyHashable : Any], andRequestMethod: YTKRequestMethod.POST, andCache: false, andCacheTime: 0, andPostToken: true)
        
        API.starRequest { (status, mess, response) in
            
            guard let dic:Dictionary = response as? [String : AnyObject] else{
                
                return
            }
            
            if status.rawValue == 1  {
                let mode1  = CourseDetail.init(DIC: dic)
                self.data = mode1.data as? ArticleDetail
                self.titleView?.mode = self.data
                //self.data?.attachFiles?.count
                
                let str :NSString = "\(String(describing: self.data!.attachFiles!.count))" as NSString
                
              let countStr =  NSString.localizedStringWithFormat("附件(%@个)", str)
                self.attatchMentLabel.text = countStr as String
                self.tableView.reloadData()
                
            }else if (status.rawValue == 404){
                
                UIAlertView.bk_show(withTitle: mess, message: "", cancelButtonTitle: "登陆", otherButtonTitles: ["取消"], handler: { (alertView, buttonIndex) in
                    if(buttonIndex == 1){
                        
                        
                        self.gotoLogin()
                        
                    }
                })
                
                
            }
            }
        //sleep(2)
        self.tableView.reloadData()
        
        
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 1 {
            let view = UIView(frame: CGRect.init(x: 0, y: 0, width: kScreenW, height: 41))
            
            attatchMentLabel.font = UIFont.systemFont(ofSize: 14)
            let lineView:UIView = UIView(frame: CGRect.init(x: 10, y: 40, width: kScreenW-20, height: 1))
            lineView.backgroundColor = UIColor.groupTableViewBackground
            view.addSubview(attatchMentLabel)
            view.addSubview(lineView)
            
            return view
        }else{
            
            return UIView()
        }
        
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 42
        }else{
            return 0
            
        }
        
    }
}


extension UIViewController{
    
    func gotoLogin(){
        
        
        LoginStatuesModel.cleanUserInfor()
        let app:AppDelegate = UIApplication.shared.delegate as! AppDelegate
        app.initUserManager()
        
        
        
        
    }
    
    
    
}
func gotoLogin(){
    
    
    LoginStatuesModel.cleanUserInfor()
    let app:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    app.initUserManager()
    
    
    
    
}







